package com.lysj.lyd_pay.wx.feignImpl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.common.collect.Maps;
import com.jpay.ext.kit.PaymentKit;
import com.lysj.admin.utils.web.HttpUtil;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.lyd_pay.util.WXPayUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

/**
 * @author Created by wtl on 2019-04-11 17:40
 * @description
 */
@RestController
@RequestMapping("/test")
public class TestController {



    @GetMapping("/native_pay")
    public void nativePay() throws Exception {
        QrCodeUtil.generate(getCodeUrl(),300,300, FileUtil.file("d:/qrcode.jpg"));
    }

    /**
     * @author Created by wtl on 2019/4/11 18:31
     * @Description 微信支付获得code_url
     */
    public String getCodeUrl() throws Exception {
        HashMap<String, String> paramMap = Maps.newHashMap();
        paramMap.put("trade_type", "NATIVE"); //交易类型
        paramMap.put("spbill_create_ip","123"); //本机的Ip
        paramMap.put("product_id", "123"); // 商户根据自己业务传递的参数 必填
        paramMap.put("body", "微信支付");         //描述
        paramMap.put("out_trade_no", "2019041100750292717"); //商户 后台的贸易单号
        paramMap.put("total_fee", "" + 1); //金额必须为整数  单位为分
        paramMap.put("notify_url", "http://2k02201u80.imwork.net/order/management/wx_order_callback"); //支付成功后，回调地址
        paramMap.put("appid", "wx1277609cd78d0e26"); //appid
        paramMap.put("mch_id", "1530626231"); //商户号
        paramMap.put("nonce_str", ParamUtil.uuid());  //随机数
        paramMap.put("sign", PaymentKit.createSign(paramMap, "EA8B650F98294219A54098AA4AFF5D98"));//根据微信签名规则，生成签名
        String xmlData = WXPayUtil.mapToXml(paramMap);//把参数转换成XML数据格式

        //统一支付接口
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String resXml = HttpUtil.sendPost(createOrderURL,xmlData);
        System.err.println(resXml);
        Document dd = null;
        String code_url=null;
        try {
            dd = DocumentHelper.parseText(resXml);
        } catch (DocumentException e) {
            return "";
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return "";
            }
            Element codeUrl = root.element("code_url");
            if (codeUrl == null) {
                return "";
            }
        }
        return code_url;  //解析 xml 获得 code_url
    }


}
